package cn.webdai.activemq.test;

import cn.webdai.activemq.pojo.MessageModel;
import com.alibaba.fastjson.JSON;
import org.apache.activemq.ScheduledMessage;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import javax.jms.*;
import java.io.Serializable;

/**
 * @author 戴金华
 * @date 2019-12-30 18:10
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class MessageSender {


    @Autowired
    private Queue queue;

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;


    /**
     * 发送消息
     */
    @Test
    public void send(){
        String message = "消息发送activemq";
        jmsMessagingTemplate.convertAndSend(queue,message);
    }


    //发送延迟消息
    @Test
    public void sendDelayMessage(){
        MessageModel messageModel = new MessageModel();
        messageModel.setTitle("延迟消息发送测试");
        messageModel.setMessage("延迟消息的具体内容");
        String json = JSON.toJSONString(messageModel);
        ConnectionFactory connectionFactory = jmsMessagingTemplate.getConnectionFactory();
        try {

            //获取连接
            Connection connection = connectionFactory.createConnection();
            //获取session
            Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            //创建一个消息队列
            Destination destination = session.createQueue("delayQueue");
            MessageProducer producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            ObjectMessage message = session.createObjectMessage((Serializable) json);
            //设置延迟时间
            message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY,5*1000);
            //发送
            System.out.println("发送的时间是"+System.currentTimeMillis());
            producer.send(message);
            session.commit();
            producer.close();
            connection.close();
        }catch (Exception e){
            e.getMessage();
        }
    }
}
